package com.genius.reservation.common.methodArgReslover;

import com.genius.reservation.tools.annotation.CurrentUser;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class TokenToUser implements HandlerMethodArgumentResolver { //处理程序方法参数解析器
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //如果该参数注解有@CurrentUser且参数类型是User
        //方法 获取参数的注解
        return methodParameter.getParameterAnnotation(CurrentUser.class) != null ;
//                &&methodParameter.getParameterType()== User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //取得HttpServletRequest
        HttpServletRequest request= (HttpServletRequest) nativeWebRequest.getNativeRequest();
        //请求中取出session中的属性 currentuser
        return request.getSession().getAttribute("currentUser");
//        return (User)request.getSession().getAttribute("currentUser");
    }
}
